layui.use(['table', 'admin', 'ax','layer','form','laytpl'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var layer=layui.layer;
    var form=layui.form;
    var laytpl=layui.laytpl;
    /**
     * 备货区分配管理
     */
    var HxStorageCenter = {
        tableId: "data-table-body"
    };

    var tableData = [
    ];
    // var tableData = Array.from({ length: 20 }, function() { return {}; });

    var currentStockPort = 1;
    // 初始化右侧表格
    table.render({
        elem: '#data-table-body',
        // url: '/hxStorageCenter/list',
        page: {
            layout:['limit','refresh'],
            limit: 20,
            limits: [20, 30, 50],
            curr: 1,
            groups:1
        },
        limit:20,
        cols: [[
            {field: 'stockPort', title: '备货口',sort:true},
            {field: 'getUnit', title: '门店名称'},
            {field:'操作',title:'操作',toolbar:'#tableBar'}
        ]],
        data: tableData,
    });

    // 定义添加行的函数
    function addRow() {
        var rangeVal = $('input[name="range"]').val();
        var rangeArr = rangeVal.split('-');
        var start = parseInt(rangeArr[0]);
        var end = parseInt(rangeArr[1]);
        $('#data-table-body').empty();
        for (var i=start;i<=end;i++){
            tableData.push({"stockPort": "" + currentStockPort, "getUnit": ""});
            currentStockPort++;
        }

        // 添加新的行到表格数据
        // tableData.push({"stockPort": "" + currentStockPort, "getUnit": ""});

        // 更新表格
        table.reload('data-table-body', {
            data: tableData
        });
        // 更新备货口序号
        // currentStockPort++;

    };

    // 绑定添加按钮的点击事件
    document.getElementById('addButton').addEventListener('click', addRow);

    //点击分配
    $('.allocate-btn').click(function () {
    layer.open({
        type:1,
        title:'分配门店',
        content:$('#popup'),
        area:['500px','300px'],
        btn:['提交','取消'],
        page: {
            layout:['limit','refresh'],
            limit: 20,
            limits: [20, 30, 50]
        },
        yes:function (index,layero) {
            var  data={
                stockPort:$("#stockPort").val(),
                getUnit:$("#getUnit").val()
            };
            console.log(data);
            // 获取到要分配的哪个信息
              var val = layero.find('select[name="select"]').val();
              var val1 = layero.find('input[name="input"]').val();
            console.log(val);
            console.log(val1);
            var newshuju=[
                    {"stockPort":val1,"getUnit":val}
            ];
            console.log(newshuju);
            //
            // var html = '<tr>';
            // html += '<td>' + val1 + '</td>';
            // html += '<td>' + val + '</td>';
            // html += '<td><button class="layui-btn layui-btn-sm clear-btn">清空</button><button class="layui-btn layui-btn-sm delete-btn">删除</button></td>';
            // html += '</tr>';
            //
            // $('#data-table-body').append(html);
            // tableData.push({stockPort:val1,getUnit:val});

            $.each(newshuju,function (index,item) {
                var isExist=false;
                $.each(tableData,function (index2,item2) {
                    if (item.stockPort===item2.stockPort){
                        tableData[index2]=item;
                        isExist=true;
                        return false;
                    }
                });
                if (!isExist){
                    tableData.push(item);
                }
            }),
            // concat = tableData.concat(newshuju);
            table.reload('data-table-body',{
               data:tableData
            });
            // $('#data-table-body').append(concat);
            $.post('/hxStorageCenter/insert',data,function (res) {
                if (res===1){
                    layer.msg('分配成功');
                    console.log(res);
                    // $(".layui-icon-refresh").click();
                }else{
                    console.log(res);
                    layer.msg('分配失败');
                };
            });
            layer.close(index);
        },
    });

});
    //添加
    $(document).on('click','add-all',function (data) {
        var oldData = table.cache["data-table-body"];

        var data1={};
        oldData.push(data1);
        table.reload('data-table-body',{data : oldData});
    });
// 清空按钮的点击事件
    $(document).on('click', '.clear-btn', function(){
        var $row = $(this).closest('tr');
        // $row.find('td:not(:last-child)').empty();
        $row.find('td:nth-child(2)').empty();
    });
    // 删除按钮的点击事件
    $(document).on('click', '.delete-btn', function(){
        var $row = $(this).closest('tr');
       $row.find('td:not(:last-child)').empty();


    });
    // 将门店信息查回，展示到左面表格中
        table.render({
            elem:'#orderTable',
            url: '/hxStorageCenter/chaxun',
            type:'post',
            dataType:'json',
            page: {
                layout:['limit','refresh'],
                limit: 20,
                limits: [20, 30, 50]
            },
            parseData:function (res) {
                console.log(res);
                return{
                    "code":0,
                    "msg":"",
                    "count":1000,
                    "data":res
                }
            },
            cols:[[
                {field:'getUnit',title:'门店名称',sort:true},
                {field:'num',title:'数量',sort:true},
                {field:'outVolume',title:'体积',sort:true},
                {field:'stockPort',title:'备货口',sort:true},
                {field:'操作',title:'操作',toolbar:'#tablefen'}
            ]],


        });
        // 弹出框的门店信息
    $.ajax({
    url: '/hxStorageCenter/chaxun',
    type:'post',
    dataType:'json',

    success:function (data) {
        JSON.stringify(data);
        console.log(data);
        if (data!==null){
            $("#getUnit").empty();
            $("#getUnit").append(new Option("请选择","0"));
            $.each(data,function (index,item) {
                $('#getUnit').append(new  Option(item.getUnit));
            });  $(".layui-icon-refresh").click();
        }else {
            $("#getUnit").append(new Option("暂无数据",""));
        }
        form.render("select");

    }
});

    /**
     * 初始化表格的列
     */
    HxStorageCenter.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键id'},
            {field: 'stockPort', sort: true, title: '备货口'},
            {field: 'getUnit', sort: true, title: '门店名称'},
            // {field: 'deptId', sort: true, title: '支付id'},
            // {field: 'deliverId', sort: true, title: '交付id'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    HxStorageCenter.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        table.reload(HxStorageCenter.tableId, {
            where: queryData, page: {curr: 1},
            done:function () {
                // 搜索按钮点击事件
                $('#btnSearch').click(function () {
                    HxStorageCenter.search();
                });
                // 添加按钮点击事件
                $('#btnAdd').click(function () {
                    HxStorageCenter.openAddDlg();
                });
                // 导出excel
                $('#btnExp').click(function () {
                    HxStorageCenter.exportExcel();
                });
            }
        });
    };

    /**
     * 弹出添加对话框
     */
    HxStorageCenter.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/hxStorageCenter/add';
    };

    /**
     * 导出excel按钮
     */
    HxStorageCenter.exportExcel = function () {
        var checkRows = table.checkStatus(HxStorageCenter.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    HxStorageCenter.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/hxStorageCenter/edit?id=' + data.id;
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    HxStorageCenter.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/hxStorageCenter/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(HxStorageCenter.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + HxStorageCenter.tableId,
        url: Feng.ctxPath + '/hxStorageCenter/list',
        // page: true,
        page: {
            layout:['limit','refresh'],

            limits: [10, 12, 15]
        },limit: 20,
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: HxStorageCenter.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        HxStorageCenter.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        HxStorageCenter.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        HxStorageCenter.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + HxStorageCenter.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            HxStorageCenter.openEditDlg(data);
        } else if (layEvent === 'delete') {
            HxStorageCenter.onDeleteItem(data);
        }
    });
});
